module.exports = function ($scope, $resource, $modal, $modalInstance, toaster, sale_info, $timeout, Excel, channel_list_code,subsidy_fee,city) {

    $scope.getBalance = function(){
        $scope.supplier_balance = 0;
        $scope.platform_balance = 0;
        $resource('/api/as/pc/bmaccount/getBalanceByCodeList', {}, {}).save({'company_code': sale_info.company_code}, function (res) {
            if (res.errcode === 0) {
                res.data.forEach(element => {
                    if(sale_info.company_code == element.supplier_company_code){
                        $scope.supplier_balance = element.balance_price * 0.01;
                    } else if('SYS' == element.supplier_company_code){
                        $scope.platform_balance = element.balance_price * 0.01;
                    }
                });
            }
        });
    }
    $scope.getBalance();
    var subsidy_type = "2018HMLYSubsidy";
    $scope.subsidy_fee = subsidy_fee;
    $scope.userList = [];
    $scope.sale_info = sale_info;
    $scope.order_info = {
        'tour_date': '',
        'pay_method': 'credit'
    };
    $scope.order_info.date = {
        'value': $scope.sale_info.price_type == '1' ? '': date2str(new Date()),
        'opened': false
    };

    //添加购票人
    $scope.add = function () {
        $scope.userList.push({
            sale_code: $scope.sale_info.sale_code,
            name: '',
            cardno: '',
            mobile: '',
            num: 1,
            note: '',
            desc: '未校验',
            state: 2
        })
    }

    //删除购票人
    $scope.remove = function (index) {
        $scope.userList.splice(index, 1);
    }

    //删除所有购票人
    $scope.removeAll = function (index) {
        $scope.userList = [];
    }

    //导入excel
    $scope.excel = function () {
        var modalInstance = $modal.open({
            template: require('../views/addUserBatch.html'),
            controller: 'addUserBatch',
            size: 'lg',
            resolve: {
            }
        });
        //关闭模态框刷新页面
        modalInstance.result.then(function (result) {
            if (result && result.length > 0) {
                for (let index = 0; index < result.length; index++) {
                    const element = result[index];
                    element.num = parseInt(element.num) || 1;
                    element.sale_code = $scope.sale_info.sale_code;
                    element.state = '2';
                    element.desc = '未校验';
                    $scope.is_pass(element)
                    $scope.userList.push((element))
                }
            }
        });
    }

    //导出Excel
    $scope.ExcelName = date2str(new Date());
    $scope.exportToExcel = function (tableId) {
        $timeout(function () {
            document.getElementById("dlink").href = Excel.tableToExcel(tableId, 'sheet1');
            //document.getElementById("dlink").download = "1122b.xls";//这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
            document.getElementById("dlink").click();
        }, 100); // trigger download
    }

    //价格日历
    $scope.selectDate = function () {
        sale_info.code = sale_info.sale_code;
        var modalInstance = $modal.open({
            template: require('../views/sellPriceSetting.html'),
            controller: 'sellPriceSetting',
            size: 'lg',
            resolve: {
                items: function () {
                    return {
                        saleobj: sale_info
                    };
                }
            }
        });
        modalInstance.opened.then(function () {// 模态窗口打开之后执行的函数  
        });
        modalInstance.result.then(function (result) {
            $scope.order_info.date.value = date2str(new Date(result.date));
        }, function (reason) {
        });
    }

    //确定购票
    $scope.ok = function () {
        if ($scope.order_info.date.value == null) {
        } else if (typeof $scope.order_info.date.value === 'string') {
            $scope.order_info.tour_date = $scope.order_info.date.value;
        } else {
            $scope.order_info.tour_date = date2str($scope.order_info.date.value);
        }
        $scope.createOrder(0);
    }
    //实际下单
    $scope.createOrder = function (index) {
        if(index >= $scope.userList.length){
            return false;
        }
        const order_info = $scope.userList[index];
        order_info.is_creating = true;
        if (order_info.state == 4 || (order_info.state != 1 && !$scope.is_pass(order_info))) {
            order_info.is_creating = false;
            $scope.createOrder(++index);
            return false;
        }
        order_info.state = 3;
        order_info.desc = '下单中';
        let para = {
            sale_code: $scope.sale_info.sale_code,
            cardno: order_info.cardno,
            name: order_info.name,
            mobile: order_info.mobile,
            num: order_info.num,
            note: order_info.note,
            tour_date: $scope.order_info.tour_date,
            pay_method: $scope.order_info.pay_method,
            channel_list_code: channel_list_code
        }
        var url = '';
        if(subsidy_fee){
            url = '/api/ac/tc/ticketOrderService/createOrderSubsidy';
            para.order_actual_Subsidy = $scope.usedSubsidy;
            para.subsidy_id = subsidy_type;
            if(para.num != 1){
                toaster.warning({ title: '', body: '本产品使用补贴只能购买一张'});
                return;
            }
        } else {
            url = '/api/ac/tc/ticketOrderService/createOrder';
        }
        $resource(url, {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                order_info.is_creating = false;
                order_info.desc = `【下单成功】${res.data}`;
                order_info.state = 4;
                toaster.success({ title: order_info.name, body: res.errmsg });
            } else {
                order_info.state = 2;
                order_info.desc = res.errmsg;
                order_info.is_creating = false;
                toaster.error({ title: order_info.name, body: res.errmsg });
            }
            $scope.createOrder(++index);
        });
    }

    //取消
    $scope.close = function () {
        $modalInstance.dismiss('cancel');
    }

    //校验
    $scope.is_pass = function (obj) {
        if (obj.state == 4) {
            return false;
        }
        obj.state = 3;
        let nocard = false;
        if (obj.cardno == '') {
            nocard = true;
            obj.desc = '未填写身份证';
        } else if (!checkCardNo(obj.cardno)) {
            obj.state = 2;
            obj.desc = '身份证信息有误';
            return false;
        }
        if (obj.name == "") {
            obj.state = 2;
            obj.desc = '请填写姓名';
            return false;
        }
        if (!isMobil(obj.mobile)) {
            obj.state = 2;
            obj.desc = '请输入正确电话号码';
            return false;
        }
        if(subsidy_fee && obj.num != 1){
            obj.state = 2;
            obj.desc = '本产品使用补贴只能购买一张';
            return false;
        }
        if (isNaN(obj.num)) {
            obj.state = 2;
            obj.desc = '购买数量请输入正确数字';
            obj.num = 0;
            return false;
        }
        if (obj.num == "0") {
            obj.state = 2;
            obj.desc = '请填写购票数量';
            return false;
        }
        if ($scope.sale_info.tour_date_type == '1' && obj.tour_date == '') {
            obj.state = 2;
            obj.desc = '请填写出游时间，该票种只能在填写的出游时间使用。';
            return false;
        }
        if (!nocard) {
            obj.desc = '校验通过';
        }
        if(subsidy_fee){
            obj.desc = '校验中';
            var para = {
                "mobile": obj.mobile,
                "name": obj.name,
                "cardno": obj.cardno,
                "subsidy_id": subsidy_type
            }
            ///api/ac/puc/pubSubsidyFXDService/createSubsidyUserInfoByCardno可领补贴接口
            $resource('/api/ac/puc/pubSubsidyFXDService/getSubsidyUserInfoByCardno', {}, {}).save(para, function (res) {
                if (res.errcode === 0) {
                    if(res.data.city == '11' || res.data.city == '2101' || city.indexOf('2101') == 0){
                        obj.state = 1;
                        $scope.usedSubsidy = subsidy_fee < res.data.subsidy_num ? subsidy_fee : res.data.subsidy_num;
                        obj.desc = '剩余补贴 ' + (res.data.subsidy_num * 0.01) + ' 元,本产品可用 ';
                        obj.desc += ($scope.usedSubsidy * 0.01) + ' 元';
                    } else if(city.indexOf('2101') != 0){
                        obj.state = 2;
                        obj.desc = '此用户身份证号无法购买此景区产品';
                    } else {
                        obj.state = 2;
                        obj.desc = '无可用补贴';
                    }
                } else{
                    obj.state = 2;
                    obj.desc = res.errmsg;
                }
            });
        } else {
            obj.state = 1;
        }

        return true;
    }

    //校验身份证
    var checkCardNo = function (code) {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        var tip = "";
        var pass = true;
        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            tip = "身份证号格式错误";
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            tip = "身份证地址编码错误";
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = "身份证校验位错误";
                    pass = false;
                }
            }
        }
        return pass;
    }

    //日期格式转换
    function date2str(d) {
        if (d === undefined) {
            return "";
        }
        var month = (d.getMonth() + 1).toString();
        var day = d.getDate().toString();
        if (month.length == 1) month = '0' + month;
        if (day.length == 1) day = '0' + day;
        return d.getFullYear() + "-" + month + "-" + day;
    }

    //打开日历控件面板
    $scope.open = function ($event, item) {
        $event.preventDefault();
        $event.stopPropagation();
        item.opened = true;
    }
    /**
     * 验证手机号
     * @param {需要校验的手机号} mobile
     * @return 错误返回 false , 正确返回 true
     */
    function isMobil(mobile) {
        var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
        if (!patrn.exec(mobile)) {
            return false;
        }
        return true;
    }
};